<?php

namespace app\api\controller;

use app\api\model\WechatCardCode;
use app\api\model\WechatCard;
use app\api\model\SearchWord;
use think\Controller;
use app\common\model\User;



class Card extends Base
{
    protected $wechatCard;
//    protected $beforeActionList = [
//        'checkToken'=>['except'=>'list,groupList']
//    ];

    protected function _initialize()
    {
        parent::_initialize();
    }

    //根据分类来获取优惠券列表
    public function catList($cat_id,$area_id)
    {
        //从微信服务器获取卡券列表
//        $cardList = session('card_list_'.$this->appletId);
//        $cardList = [];
//        if(empty($cardList)){
//            $this->wechatCard = new \app\mpbase\library\WechatCard();
//            $cardList = $this->wechatCard->cardList();
//            session('card_list_'.$this->appletId,$cardList);
//        }
//        $res['data'] = $cardList;
//        return self::apiResp($res);

        $row = input('row', 10);
        $page = input('page', 1);
		$map = ['cat_id'=>$cat_id,'area_id'=>$area_id];
        $data = WechatCard::getList($map, $page, $row);

        return self::apiResp($data);
    }

	//根据id来获取优惠券详情
	public function getById($id)
	{
		$map = ['id' => $id];
		$data = WechatCard::getById($map);
		return self::apiResp($data);
	}


    public function activateCard()
    {
        $this->wechatCard = new \app\mpbase\library\WechatCard();
        $res = $this->wechatCard->addCardExt();
    }

    //生成领取卡券的 cardExt
    public function card_ext()
    {
        if(input('card_id')=='')
            $res = ['_code'=>400,'msg'=>'card_id不能为空'];
        else{
            $this->wechatCard = new \app\mpbase\library\WechatCard();
            $res = $this->wechatCard->addCardExt();
        }
        return self::apiResp($res);
    }

    //保存领取的卡券Code、CardId
    public function save_code()
    {
        $res = WechatCardCode::saveCode(
            get_api_applet_id(),
            $this->userId,
            input('post.'));
        return self::apiResp($res);
    }

    //检查卡券Code 并同步 状态
    public function check_code()
    {
        $decryptCode = input('post.decrypt_code');
        $this->wechatCard = new \app\mpbase\library\WechatCard();
        $res = $this->wechatCard->checkCode($decryptCode);
        if($res['errcode'] == 0 && $res['errmsg'] == 'ok'
            && !$res['can_consume'] ){
            WechatCardCode::setState($decryptCode,$res['user_card_status']);
        }
        return self::apiResp($res);
    }

    //保存领取的卡券Code、CardId
    public function delete_code()
    {
        $decryptCode = input('post.decrypt_code');
        $code = WechatCardCode::get(['decrypt_code'=>$decryptCode]);
        if(!$code){
            $res = ['_code'=>'400','msg'=>'该卡券不存在'];
        }else{
            $res = WechatCardCode::deleteCode($decryptCode,true);
        }
        return self::apiResp($res);
    }

    //优惠券列表
    public function my_list()
    {
        $row = input('row', 10);
        $page = input('page', 1);
        $data = WechatCard::getListByUser($this->userId, $page, $row);
        return self::apiResp($data);
    }

    //依据in条件,group主题下
	public function groupList($list)
	{
		$map = $list;
		$data = (new WechatCard())->groupList($list);
		return self::apiResp($data);
	}

	public function couponPage($area_id)
	{

		//判断条件
		$order = [];
		$arr = [];
		$map = [];
		$distance = input('distance');
		$longitude = input('longitude');
		$latitude = input('latitude');
		$cat_id = input('cat_id');
		$time = input('time');
		$map['card.area_id'] = $area_id;

        //分页
		$page = input('page',1);
		$row = input('row',10);

		//判断有无距离排序
	    if($distance){
            $order['distance'] = $distance;
		}

		if($longitude && $latitude){
			$arr['lng'] = $longitude;
			$arr['lat'] = $latitude;
		}else{
			$res = ['_code'=>'400','msg'=>'距离排序请输入经纬度'];
			return self::apiResp($res);
		}

		//判断是否日期排序
		if($time){
			$order['card.end_timestamp'] = $time;
		}

        //判断有无分类
		if($cat_id){
			$map['card.cat_id'] = $cat_id;
		}

		$data = (new WechatCard())->couponPage($map,$order,$arr,$page,$row);
		return self::apiResp($data);
	}

	//获取用户领取的优惠券
	public function getUserCard()
	{
        $id = input('id');
        $mp_openid = User::where(['id' => $id])->find()['mp_openid'];
        if(!$mp_openid) {
            //openid为空的情况
            $data = ['_code'=>'400','msg'=>'用户暂时没有领券','data'=>[]];
        }else{
            $data = WechatCard::getUserCard($mp_openid);
        }
        return self::apiResp($data);
	}

    //获取用户核销掉的卡券
    public function getConsumeCard()
    {
        $id = input('id');
        $mp_openid = User::where(['id' => $id])->find()['mp_openid'];
        if(!$mp_openid){
            //openid为空的情况
            $data = ['_code'=>'400','msg'=>'用户暂时没有领券','data'=>[]];
        }else{
            $data = WechatCard::getConsumeCard($mp_openid);
        }
        return self::apiResp($data);
    }

    //获取用户全部卡券
    public function getAllCard()
    {
        $mp_openid = input('mp_openid');

    }

	public function searchCard()
    {
        $area_id = input('area_id');
        $word = input('word');
        $longitude = input('longitude');
        $latitude = input('latitude');
        $page = input('page',1);
        $row = input('row',3);

        if(!$word){
            $res = ['_code'=>'400','msg'=>'请输入关键词'];
            return self::apiResp($res);
        }

        if($longitude && $latitude){
            $arr['lng'] = $longitude;
            $arr['lat'] = $latitude;
        }else{
            $res = ['_code'=>'400','msg'=>'距离排序请输入经纬度'];
            return self::apiResp($res);
        }
        $map['card.area_id'] = $area_id;
        $map['store.s_name|card.title'] = ['like','%'.$word.'%'];
        //加入关键字
        $search = (new SearchWord)->addWord($word);
        $data = (new WechatCard())->couponPage($map,[],$arr,$page,$row);
//        foreach($data['data'] as &$v){
//            $v['s_name'] = str_replace($word,"<text class='red'>".$word.'</text>',$v['s_name']);
//            $v['title'] = str_replace($word,"<text class='red'>".$word.'</text>',$v['title']);
//        }
        return self::apiResp($data);
    }


}
